package com.jihox.abookpro;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.jihox.abookpro.R;
import com.jihox.abookpro.util.AndroidImageFile;
import com.jihox.abookpro.util.NativeImageLoader;
import com.jihox.abookpro.util.NativeImageLoader.NativeImageCallBack;
import com.jihox.abookpro.view.ZoomImageView;

/**
 * 查看大图的Activity界面。
 */
public class ImageDetailsActivity extends BaseActivity implements OnPageChangeListener {

	/**
	 * 用于管理图片的滑动
	 */
	private ViewPager viewPager;

	/**
	 * 显示当前图片的页数
	 */
	private TextView pageText;

	private Button deleteButton;
	private Button cancelButton;
	private int currentIndex;

	private ImagesObserver imagesObserver;

	private String ZOOM_VIEW_SUFFIX = "zoomViewSuffix";

	private int screenWidth = 1000;

	private int screenHeight = 2000;
	
	private ViewPagerAdapter adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		WindowManager wm = this.getWindowManager();
		screenWidth = wm.getDefaultDisplay().getWidth();
		screenHeight = wm.getDefaultDisplay().getHeight();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.image_details);
		currentIndex = getIntent().getIntExtra("image_position", 0)+1;
		pageText = (TextView) findViewById(R.id.page_text);
		viewPager = (ViewPager) findViewById(R.id.view_pager);
		deleteButton = (Button) findViewById(R.id.button_delete);
		cancelButton = (Button) findViewById(R.id.button_keep);
		adapter = new ViewPagerAdapter();
		viewPager.setAdapter(adapter);
		viewPager.setCurrentItem(currentIndex);
		viewPager.setOnPageChangeListener(this);
		viewPager.setEnabled(true);
		deleteButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ShowImageActivity.selectedPhotoList.remove(currentIndex-1);
				if(ShowImageActivity.selectedPhotoList.size() <= 0)
				{
					onBackPressed();
				}
				else if(currentIndex > ShowImageActivity.selectedPhotoList.size())
				{
					adapter.notifyDataSetChanged();
					viewPager.setCurrentItem(viewPager.getCurrentItem()-1,true);
				}
				else 
				{
					adapter.notifyDataSetChanged();
					refershPageText();
				}
				
			}
		});
		cancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		// 设定当前的页数和总页数
		pageText.setText(currentIndex  + "/" + ShowImageActivity.selectedPhotoList.size());
		imagesObserver = new ImagesObserver(new Handler()){
			@Override
			public void onChange(boolean selfChange) {
				if(!checkSelectedList()){
					Intent intent = new Intent();    
					intent.setClass(ImageDetailsActivity.this, GallerySelectActivity.class);   
					ImageDetailsActivity.this.startActivity(intent);
					finish();
				}
			}
		};
		this.getContentResolver().registerContentObserver( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, imagesObserver); 

	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		getContentResolver().unregisterContentObserver(imagesObserver);
		super.onDestroy();
	}
	/**
	 * ViewPager的适配器
	 * 
	 * @author guolin
	 */
	class ViewPagerAdapter extends PagerAdapter {

		@Override
		public synchronized Object instantiateItem(ViewGroup container, final int position) {

			View view = LayoutInflater.from(ImageDetailsActivity.this).inflate(
					R.layout.zoom_image_layout, null);
			if(position==0||position==getCount()-1){
				return view;
			}
			ZoomImageView zoomImageView = (ZoomImageView) view
					.findViewById(R.id.zoom_image_view);
			zoomImageView.setTag(position+ZOOM_VIEW_SUFFIX);
			Bitmap bitmap = NativeImageLoader.getInstance().loadNativeImageForDetail(ShowImageActivity.selectedPhotoList.get(position-1), null, new NativeImageCallBack() {
				@Override
				public void onImageLoader(Bitmap bitmap, AndroidImageFile aif) {
					ZoomImageView mZoomImageView =  (ZoomImageView) viewPager.findViewWithTag(position+ZOOM_VIEW_SUFFIX );
					if(bitmap != null && mZoomImageView != null){
						mZoomImageView.setImageBitmap(bitmap);
					}
				}  
			});  

			if (bitmap == null) {
				bitmap = Bitmap.createBitmap(screenWidth, screenHeight, Config.RGB_565);
			}

			zoomImageView.setImageBitmap(bitmap);

			container.addView(view);
			return view;
		}

		@Override
		public int getCount() {
			return ShowImageActivity.selectedPhotoList.size()+2;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getItemPosition(Object object)
		{
			return POSITION_NONE;
		}
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			View view = (View) object;
			container.removeView(view);
		}

	}

	//	/**
	//	 * 获取图片的本地存储路径。
	//	 * 
	//	 * @param imageUrl
	//	 *            图片的URL地址。
	//	 * @return 图片的本地存储路径。
	//	 */
	//	private String getImagePath(String imageUrl) {
	//		int lastSlashIndex = imageUrl.lastIndexOf("/");
	//		String imageName = imageUrl.substring(lastSlashIndex + 1);
	//		String imageDir = Environment.getExternalStorageDirectory().getPath()
	//				+ "/PhotoWallFalls/";
	//		File file = new File(imageDir);
	//		if (!file.exists()) {
	//			file.mkdirs();
	//		}
	//		String imagePath = imageDir + imageName;
	//		return imagePath;
	//	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int currentPage) {
		// 每当页数发生改变时重新设定一遍当前的页数和总页数
		currentIndex = currentPage;
		ZoomImageView zoomImageView = (ZoomImageView) viewPager.findViewWithTag(currentPage+ZOOM_VIEW_SUFFIX );
		if(zoomImageView!=null){
			zoomImageView.resetTotalRatio();
		}
		if(currentPage==0){
			viewPager.setCurrentItem(1);
		}else if(currentPage==ShowImageActivity.selectedPhotoList.size()+1){
			viewPager.setCurrentItem(ShowImageActivity.selectedPhotoList.size());
		}else{
			refershPageText();
		}
	}
	//刷新下方的页码
	private void refershPageText()
	{
		pageText.setText((currentIndex) + "/" + ShowImageActivity.selectedPhotoList.size());
	}

}